package com.atsmart.app.receiver;

import java.util.ArrayList;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.activity.LoginActivity;
import com.atsmart.app.activity.PushNotificationActivity;
import com.atsmart.app.model.CheckDurationInfo;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.PositionInfo;
import com.atsmart.app.model.PositionShutDownInfo;
import com.atsmart.app.model.PositonsInfo;
import com.atsmart.app.sql.ClientSqlHelper;
import com.atsmart.app.sql.ContextSqlHelper;
import com.atsmart.app.sql.ProductItemSqlHelper;
import com.atsmart.app.sql.ProductSqlHelper;
import com.atsmart.app.sql.SelectInfoSql;
import com.atsmart.app.sql.ShutDownSqlHelper;
import com.atsmart.app.sql.TaskInfoSqlHelper;
import com.atsmart.app.sql.TempFromTaskSql;
import com.atsmart.app.sql.TemplateDetailSql;
import com.atsmart.app.sql.TemplateInfoSql;
import com.atsmart.app.sql.UserInfoSql;
import com.atsmart.app.utils.LocationUtils;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.atsmart.log.UserLog;
//import com.atsmart.log.UserLog;
import com.google.json.Gson;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class JpushReceive extends BroadcastReceiver {
	private static final String TAG = "MyReceiver";
	private String title = "";
	private Context context;
	private UserInfoSql userInfoSql = null;
	
	String content;
	private PowerManager.WakeLock wakeLock = null;
	@Override
	public void onReceive(Context context, Intent intent) {
		this.context = context;
		try{
			Bundle bundle = intent.getExtras();
			Log.e(TAG, "onReceive - " + intent.getAction());
//			if (bundle != null) {
//				title = bundle
//						.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
//				content = bundle.getString(JPushInterface.EXTRA_ALERT);
//			}
			Log.e("title", "title: = " + title + " , content: = " + content);

			if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
					 String regId =
					 bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
					 Log.e(TAG, "接收Registration Id : " + regId);
	            //发送到服务器的注册ID
	        }else if (JPushInterface.ACTION_UNREGISTER.equals(intent.getAction())){
	        	String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
	            Log.e(TAG, "接收UnRegistration Id : " + regId);
//	        	 注销ID发送到您的服务器
	        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
	        	Log.e(TAG, "接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
	        	 if(bundle.getString(JPushInterface.EXTRA_MESSAGE).equals("push")){
	        		 TaskInfoSqlHelper taskInfoSqlHelper = new TaskInfoSqlHelper();
	        		 taskInfoSqlHelper.open(BizApp.getInstance().getSqlHelper());
	        		 taskInfoSqlHelper.delete();
	        		 
					TemplateInfoSql templateInfoSql = new TemplateInfoSql();
					templateInfoSql.open(BizApp.getInstance().getSqlHelper());
					templateInfoSql.delete();
					
					TempFromTaskSql tesql = new TempFromTaskSql();
					tesql.open(BizApp.getInstance().getSqlHelper());
					tesql.delete();
					
					TemplateDetailSql templateDetailSql = new TemplateDetailSql();
					templateDetailSql.open(BizApp.getInstance().getSqlHelper());
					templateDetailSql.delete();
				 
					SelectInfoSql selectInfoSql = new SelectInfoSql();
					selectInfoSql.open(BizApp.getInstance().getSqlHelper());
					selectInfoSql.delete();
					
					ClientSqlHelper clientSqlHelper = new ClientSqlHelper();
					clientSqlHelper.open(BizApp.getInstance().getSqlHelper());
					clientSqlHelper.delete();
					
					ProductSqlHelper productSql = new ProductSqlHelper();
					productSql.open(BizApp.getInstance().getSqlHelper());
					productSql.deleteProItem();
					
					ProductItemSqlHelper productItemSqlHelper = new ProductItemSqlHelper();
					productItemSqlHelper.open(BizApp.getInstance().getSqlHelper());
					productItemSqlHelper.delete();
					
	        	 }
	        	 
	        	if(bundle != null){
				String content = bundle.getString(JPushInterface.EXTRA_ALERT);
				String title = bundle.getString(JPushInterface.EXTRA_TITLE);
				Log.e("位置服务推送", "title: = " + title + " , content: = " + content);
				if(userInfoSql == null){
					userInfoSql = new UserInfoSql();
					userInfoSql.open(BizApp.getInstance().getSqlHelper());
				}
				if (!StringUtil.isEmptyOrNull(title)) {
						if (title.split(",")[0].equals("3")) {// 推送通知
							try {
								if (userInfoSql != null && !StringUtil.isEmptyOrNull(userInfoSql.getAttribute())) {
									wakeLock = acquireWakeLock();
									relesseWakeLock();
									pushLoc();
								} else {
									// Log.e(TAG, "请登录商途通");
									Toast.makeText(
											context,
											"请登录"
													+ context.getResources().getString(
															R.string.app_name),
											Toast.LENGTH_SHORT).show();
									Intent intents = new Intent();
									intents.setClass(context, LoginActivity.class);
									intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
									context.startActivity(intents);
								}
							} catch (Exception e) {
							}
						}
	
					} 
		        }
					
	        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
//	            Log.e(TAG, "接收到推送下来的通知");
	            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
	            Log.e(TAG, "接收到推送下来的通知的ID: " + notifactionId);
	        	
	        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
	            Log.e(TAG, "用户点击打开了通知");
//	        	打开自定义的Activity
	        	Intent i = new Intent(context, PushNotificationActivity.class);
				i.putExtras(bundle);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(i);
	        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
	            Log.e(TAG, "用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
	            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
	        	
	        } else {
	        }
		}catch (Exception e) {
		}
	}

	private void relesseWakeLock() {
		if (wakeLock != null && wakeLock.isHeld()) {
			wakeLock.release();
			wakeLock = null;
		}
	}
	
	private PowerManager.WakeLock acquireWakeLock() {
		try {
			PowerManager localPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);  
			if (localPowerManager != null) {
				String str1 = JpushReceive.class.getName();
				PowerManager.WakeLock localWakeLock = null;
			 
				if (android.os.Build.MODEL.equals("HUAWEI Y 220T")
						|| android.os.Build.MODEL.equals("ZTE-U V880")
						|| android.os.Build.MODEL.equals("HUAWEI C8813Q")
						|| android.os.Build.MODEL.equals("ZTE V889D")) {
				 
					localWakeLock = localPowerManager.newWakeLock(
							PowerManager.SCREEN_DIM_WAKE_LOCK
									| PowerManager.ACQUIRE_CAUSES_WAKEUP, str1);
				} else {
					localWakeLock = localPowerManager.newWakeLock(
							PowerManager.PARTIAL_WAKE_LOCK, str1);

				}
				if (localWakeLock != null)
					localWakeLock.acquire();
				if (localWakeLock != null && localWakeLock.isHeld())
					localWakeLock.release();
				return localWakeLock;
			} else {
				return null;
			}

		} catch (Exception localException) {
			localException.printStackTrace();
			return null;
		}

	}
	

	private String date = "";
	private void pushLoc(){
		date = StringUtil.millToDate(BizApp.getInstance().getSendtime());
		try {
			new Thread() {
				public void run() {
					boolean ff = System.currentTimeMillis() > (BizApp
							.getInstance().getLocTime() + 70000);
//					UserLog.getInstance().write("SendReceiver ff : = " + ff + StringUtil.getCurrentTime() + " , SendReceiver lat: = " + BizApp.getInstance().getLat() +" , lon: = "+ BizApp.getInstance().getLon() + StringUtil.getCurrentTime());
					if (BizApp.getInstance().isNetworkAvailable()
							|| BizApp.getInstance().isWiFiActive()) {
						if (BizApp.getInstance().getCurrentLocation() == null
								|| BizApp.getInstance().getLat() < 0.0001
								|| BizApp.getInstance().getLon() < 0.0001 || ff) {
					
							BizApp.getInstance().getmLocationClient().start();
							try {
								sleep(7000);
								int i = 0;
								while (!BizApp.getInstance().isLocation
										&& i < 11) {
									sleep(4000);
									i++;
								}

								if (BizApp.getInstance().isLocation) {
									ff = false;
									BizApp.getInstance().isLocation = false;
								}

								BizApp.getInstance().getmLocationClient()
										.stop();
							} catch (InterruptedException e) {
//								UserLog.getInstance().writeException(e);
								e.printStackTrace();
							}

						}
					}
					if (StringUtil.isEmptyOrNull(PrefsUtils.getResult())) {
						sendloc(ff, date);
					}
				}
			}.start();
		} catch (Exception e) {
//			UserLog.getInstance().writeException(e);
			e.printStackTrace();
		}
	}
	
	/**
	 * 推送上传位置
	 */
	public void sendloc(boolean ff, String date) {
		PositionInfo position = new PositionInfo();
		Gson gson = new Gson();
		CommonBody body = new CommonBody();
		body.setCommand(2);
		body.setImsi(BizApp.getInstance().getIMSI());
		body.setVersion(BizApp.getInstance().getString(R.string.app_version));
		PositonsInfo positions = new PositonsInfo();
		positions.positions = new ArrayList<PositionInfo>();
		position.date = date;
		Double lat_now = null;
		Double lon_now = null;
		if (BizApp.getInstance().isWiFiActive() || BizApp.getInstance().isNetworkAvailable()) {
			lat_now = BizApp.getInstance().getLat();
			lon_now = BizApp.getInstance().getLon();
			position.lat = lat_now;
			position.lon = lon_now;
		} else {
			position.lat = 0.0;
			position.lon = 0.0;
		}
		position.address = "";
		position.locationMsg = LocationUtils.getInstance().getLocationMsg();
		position.msgType = 9;// 推送位置
		BizApp.getInstance().start = false;
		BizApp.getInstance().end = false;
		position.type = 1;// 高精度gps
		positions.positions.add(position);
		ShutDownSqlHelper psql = new ShutDownSqlHelper();
		psql.open(BizApp.getInstance().getSqlHelper());
		// 无网络保存本地，待有网络时上传汇报,若返回定位地址不实时则退出。
		if ((!BizApp.getInstance().isNetworkAvailable() && !BizApp.getInstance().isWiFiActive())|| BizApp.getInstance().keeping == false) {
			PositionShutDownInfo pinfo = new PositionShutDownInfo();
			if(BizApp.isWrite){
				UserLog.getInstance().writeUnIntent("位置推送 无网络写入本地 " + gson.toJson(positions));
			}
			pinfo.setVer(gson.toJson(body));
			pinfo.setPos(gson.toJson(positions));
			pinfo.setType(9);// 推送结束保存束保存
			psql.addAttribute(pinfo);
		} else {// 有网络检测sql中是否有保存内容，有--上传sql内容 无--推送位置
			PositionShutDownInfo pinfo = new PositionShutDownInfo();
			try {
				CheckDurationInfo info = ServiceHelper.getInstance()
						.postData(ServiceHost.reportLocationURL(),
								gson.toJson(body), gson.toJson(positions),
								CheckDurationInfo.class);

				if (info != null && info.getResult() == 0) {
					if(BizApp.isWrite){
//						Log.e(TAG ,"推送位置成功： = " + gson.toJson(positions) + " , 当前时间： = " + StringUtil.getCurrentTime() + "\r\t\n");
						UserLog.getInstance().writeSucessFile("推送位置成功： = " + gson.toJson(positions) + " , 当前时间： = " + StringUtil.getCurrentTime() + "\r\t\n");
					}
					// 上传成功
				} else {// 上传失败
					if(BizApp.isWrite){
//						Log.e(TAG ,"推送位置失败： = " + gson.toJson(positions) + " , 当前时间： = " + StringUtil.getCurrentTime() + "\r\t\n");
						UserLog.getInstance().writeException("推送位置失败： = " + gson.toJson(positions) + " , 当前时间： = " + StringUtil.getCurrentTime() + "\r\t\n");
					}
					pinfo.setVer(gson.toJson(body));
					pinfo.setPos(gson.toJson(positions));
					pinfo.setType(9);//推送结束保存
					psql.addAttribute(pinfo);
				}
			} catch (Exception e) {
				if(BizApp.isWrite){
					UserLog.getInstance().writeException("位置推送异常： = " + gson.toJson(positions) + " , 当前时间： = " + StringUtil.getCurrentTime() + "\r\t\n");
//					Log.e(TAG ,"推送异常： = " + gson.toJson(positions) + " , 当前时间： = " + StringUtil.getCurrentTime() + "\r\t\n");
				}
//				UserLog.getInstance().writeException(e);
				pinfo.setVer(gson.toJson(body));
				pinfo.setPos(gson.toJson(positions));
				pinfo.setType(9);// 巡检结束保存
				psql.addAttribute(pinfo);
//				e.printStackTrace();
			}
		}
	}
}
